<!-- 质量报告查看、新增、编辑、审核 -->
<template>
  <Spin :spinning="loading" tip="Loading...">
    <div>
      <div class="null-box" v-if="isNullData">暂无数据</div>
      <div class="body" v-else>
        <FormPanel ref="formPanel1" :list="editFormArr[0]" :cols="4" labelWidth="110" :isSubmitBtn="false" @formChange="formChangeHandle" />
        <template>
          <BreakSpace label="DTC信息" :containerStyle="{ marginBottom: '10px', padding: '0px 16px' }" />
          <FilterTable
            ref="table"
            :isToperInfo="false"
            :isSelectColumn="false"
            :isColumnFilter="false"
            :onColumnsChange="() => {}"
            :columns="columns2"
            :dataSource="dataList2"
            :datakey="'records'"
            :height="172"
            style="margin-bottom: 20px"
          >
          </FilterTable>
        </template>
        <FormPanel ref="formPanel2" :list="editFormArr[1]" :cols="4" labelWidth="110" :isSubmitBtn="false" @formChange="formChangeHandle2" />
        <template>
          <BreakSpace label="备件信息" :containerStyle="{ marginBottom: '10px', padding: '0px 16px' }" />
          <FilterTable
            ref="table"
            :isToperInfo="false"
            :isSelectColumn="false"
            :isColumnFilter="false"
            :onColumnsChange="() => {}"
            :columns="columns3"
            :dataSource="dataList3"
            :datakey="'records'"
            :height="172"
            style="margin-bottom: 20px"
          >
          </FilterTable>
        </template>
        <FormPanel ref="formPanel3" :list="editFormArr[2]" :cols="4" labelWidth="110" :isSubmitBtn="false" @formChange="formChangeHandle3" />
        <template v-if="!isAdd">
          <BreakSpace label="历史审核记录" :containerStyle="{ marginBottom: '10px', padding: '0px 16px' }" />
          <FilterTable
            ref="table"
            :isToperInfo="false"
            :isSelectColumn="false"
            :isColumnFilter="false"
            :onColumnsChange="() => {}"
            :columns="columns"
            :dataSource="dataList"
            :datakey="'records'"
            :height="172"
            style="margin-bottom: 20px"
          />
        </template>
        <template v-if="isShowAudit">
          <FormPanel ref="formPanel4" :list="editFormArr[3]" :cols="4" labelWidth="110" :isSubmitBtn="false" @formChange="formChangeHandle4" />
        </template>
      </div>
      <div class="footer">
        <div class="box">
          <template v-if="isDLR && !isReadonly">
            <multiuse-button type="primary" @click="handleSubmit('save')" :disabled="flag">保存</multiuse-button>
            <multiuse-button type="primary" @click="handleSubmit('submit')" :disabled="flag">上报</multiuse-button>
          </template>
          <template v-if="!isDLR && !isReadonly">
            <multiuse-button type="primary" @click="handleAudit('PASS')" :disabled="flag">通过</multiuse-button>
            <multiuse-button type="primary" @click="handleAudit('TURN')" :disabled="flag">驳回</multiuse-button>
            <!-- <multiuse-button type="primary" @click="handleAudit('REFUSE')" :disabled="flag">拒绝</multiuse-button> -->
          </template>
          <multiuse-button type="primary" @click="closeDialog" plain>返回</multiuse-button>
        </div>
      </div>
    </div>
  </Spin>
</template>
<script>
import { quyrpQaUrgent, getPartType, editSave } from '@/api/claim/dealer/QualityInformationManagement_DLR/EmergencyReturn/index';
import { isFormEmpty } from '@/utils/index';
import { copyUpdateData } from '@/utils/index';
import moment from 'moment';
import { dictionary } from '@/utils/dictMixin';
import { getUser } from '@/assets/js/auth.js';

// 接口
import { reqSave, reqDetails, reqUpadate } from '@/api/serviceass/qualityManage/feedback';
import { reqDetailsAudit } from '@/api/serviceass/qualityManage/audit';

// mock 方法
import mockFun from '@/mock/fun';
const { mockDetails } = mockFun.qualityManage.mockFunWrap(); // 涉及闭包 所以需要先调用外层函数一次 然后通过解构获取对应mock方法

import { mapGetters, mapMutations } from 'vuex';
import { isEmpty } from '@/utils/utils';
import config from '@/assets/js/config';

/**
 * 用来跳过新增操作一些判断使用，为了便于调试新增提交接口，避免每次手动录入整个表单
 * **** 生产环境下恒定为false , 即不自动填充表单
 * isAutoFillForm
 */
import { isAutoFillForm } from '../../config.js';

export default {
  mixins: [dictionary],
  props: ['rowData', 'userInfo', 'userInfoData'],
  components: {},
  data() {
    return {
      isNullData: false,
      loading: true,
      editRow: {},
      collapse: false,
      urgentStatusFlag: 5,
      infoId: null,
      fetchParams: {}, //ipa 接口
      selectedRows: [], //选中经销商
      formList: [],
      formList3: [],
      // 操作历史 列表数据源
      columns: this.creatHeader(),
      columns2: this.creatHeader2(),
      columns3: this.creatHeader3(),
      dataList: [
        // {operationStatus:'50031001',operator:'王晓丽',operationTime:'2020-09-09',instructions:'操作说明'},
      ],
      dataList2: [],
      dataList3: [],
      saveData: null,
      flag: false,
      isDisabled: true,
      /**
       * 详情表单数据(二维空数组，对应5个子表单)
       * 为了便于表单中插入操作历史模块，所以前4个为一组，后一个为一组
       */
      editFormArr: [[], []],
      // 复选框是与否
      checkBoxOptions: { trueValue: 10041001, falseValue: 10041002 },
      whatTimeList: [],
      whatTime: []
    };
  },
  created() {
    this.init();
  },
  computed: {
    ...mapGetters('qualityManage', ['pageType', 'editFormStatus', 'curEditFormData', 'isShowDialog', 'searchPartCode']),
    isDLR() {
      return this.pageType === 'DLR';
    },
    isAdd() {
      return this.editFormStatus === 'add';
    },
    isShowAudit() {
      return this.pageType === 'OEM' && this.editFormStatus === 'audit';
    },
    isReadonly() {
      return this.editFormStatus === 'readonly';
    },
  },
  methods: {
    ...mapMutations('qualityManage', ['SET_STATE_BY_NAME']),
    async init() {
      try {
        // 期望的逻辑...

        // 渲染表单（表单初始化）
        this.renderForm();

        // 表单是否可编辑
        this.isDisabled = this.hasDisabled();

        /**
         * 通过表单状态 editFormStatus 判断是否需要请求详情接口
         *    是：
         *         readonly 只读
         *         edit     编辑
         *         audit    审核
         *    否：
         *         add      新增
         */
        if (this.editFormStatus === 'add' && !isAutoFillForm) {
          // 先重置
          this.setStateParam('curEditFormData', null);
          // 渲染表单（重新渲染）
          this.renderForm();
          return;
        }

        // 是否需要自动填充
        const { reportId } = isAutoFillForm ? { reportId: '0094d5bb90ac1159a2d5c5f3dc16bbcb' } : this.rowData;
        // const funMap = {
        //   DLR: reqDetails,
        //   OEM: reqDetailsAudit,
        // };
        // const result = await mockDetails({ reportId })
        // const result = await funMap[this.pageType]({ reportId });
        const result = await reqDetails({ reportId: reportId });

        const { resultCode, message, data } = result;
        if (resultCode == 200) {
          this.dataList2 = data.dtcList;
          this.dataList3 = data.partList;
          this.whatTime = data.whatTimeList;
          this.setStateParam('curEditFormData', data);
          // 渲染表单（重新渲染）
          this.renderForm();
          this.editFormArr[0].forEach((x) => {
            if (data.refit === 10041001) {
              if(x.fieldName === 'refitRemarks'){
                x.hidden = false;
              }
            }
            this.$set(x, 'initialValue', data[x.fieldName]);
          });
          this.editFormArr[1].forEach((x) => {
            if (data.isReproduce === 10041001) {
              if (x.fieldName === 'examineDate' || x.fieldName === 'examineMile' || x.fieldName === 'faultCause' || x.fieldName === 'remedialOperation' || x.fieldName === 'maintenanceResults') {
                x.hidden = false;
              }
            }
            this.$set(x, 'initialValue', data[x.fieldName]);
          });
          this.editFormArr[2].forEach((x) => {
            this.$set(x, 'initialValue', data[x.fieldName]);
          });

          // 操作历史赋值
          const { rpLogList } = data;
          if (rpLogList && rpLogList.length > 0) {
            this.dataList = rpLogList;
          }
        } else {
          this.isNullData = true;
          this.$notify.error({ title: '提示信息', message: message || '明细获取失败' });
        }
      } catch (err) {
        // 异常处理...
        console.warn(err);
      } finally {
        // 不管正常与否均要执行的语句...
        // 关闭loading
        this.loading = false;
      }
    },
    /**
     * 判断表单项 是否为禁用状态
     */
    hasDisabled() {
      const { pageType, editFormStatus } = this;
      /**
       * 输入框状态：
       * 不可编辑：只读 readonly、 审核 audit
       * 可编辑：  新增 add 、     编辑 edit
       */
      const disabledStatus = ['readonly', 'audit'];
      const flag = disabledStatus.includes(editFormStatus);
      return flag;
    },
    /**
     * 表单渲染
     * 只要 curEditFormData 数据变更，都需要重新执行一次该方法
     */
    renderForm() {
      this.editFormArr = [
        [
          { type: 'BREAK_SPACE', label: '基础信息' },
          ...this.createFormList1(),
          { type: 'BREAK_SPACE', label: '车辆信息' },
          ...this.createFormList2(),
          { type: 'BREAK_SPACE', label: '进站信息(必填)' },
          ...this.createFormList3(),
        ],
        [
          { type: 'BREAK_SPACE', label: '故障状态(必填)' },
          ...this.createFormList5(),
          { type: 'BREAK_SPACE', label: '咨询信息(必填, 字数限制300)' },
          ...this.createFormList6(),
          { type: 'BREAK_SPACE', label: '维修信息(必填, 字数限制300)' },
          ...this.createFormList7(),
        ],
        [{ type: 'BREAK_SPACE', label: '附件信息' }, ...this.createFormList8()],
        [...this.createFormList9()],
      ];
      /**
       * 批量添加扩展字段
       */
      this.editFormArr = this.addExtendFields();
    },
    /**
     * 批量添加扩展字段
     *    ·单个字段： rules...
     *    ·公共字段： disabled readeonly placeholder...
     */
    addExtendFields() {
      let arr = [];
      /**
       * 编辑 明细 审核三个状态还需要添加初始值
       * 根据详情接口数据，添加初始值
       */
      arr = this.isAdd && !isAutoFillForm ? this.addFields() : this.addFields('init');
      return arr;
    },
    /**
     * 添加字段
     * 保障一次遍历即可处理完数据，避免多循环处理导致应用性能降低
     * @param {String} type
     */
    addFields(type) {
      const { editFormArr } = this;
      const formArr = [];
      editFormArr.forEach((arr, i) => {
        arr.forEach((item, j) => {
          // 添加公共字段(第一次)
          if (type === 'init') {
            // 添加公共字段 + 更新
            this.addCommonFields(item);
            this.updateFields(item);
          } else if (type === 'update') {
            // 仅 更新
            this.updateFields(item);
          } else {
            // 仅 添加公共字段
            this.addCommonFields(item);
          }
        });
        formArr.push(arr);
      });

      return formArr;
    },
    /**
     * 添加公共字段
     */
    addCommonFields(item) {
      const { isDisabled, isShowAudit } = this;

      // 提示语
      const valMap = { INPUT: '请输入', SELECT: '请选择', DATE: '请选择', CHECKBOX: '请选择', UPLOAD_FILE: '请上传', default: '必填字段' };
      const placeholder = `${valMap[item.type] || valMap['default']}`;

      // 验证触发方式
      const triggerMap = { INPUT: 'blur', SELECT: 'change', CHECKBOX: 'blur', default: 'blur' };
      const trigger = triggerMap[item.type] || triggerMap['default'];

      // 审核操作相关字段
      const auditFields = ['checkBy', 'checkAt', 'suggestion'];
      // 判断当前是否处于审核状态 且 遍历字段是否为审核字段
      const isHandleAudit = isShowAudit && auditFields.includes(item.fieldName);

      // 赋值(审核状态下，相关字段不禁用输入框)
      if (!item.disabled) {
        item['disabled'] = isHandleAudit ? false : isDisabled;
      }
      item['placeholder'] = placeholder;
      if (!item['rules']) {
        item['rules'] = [{ required: isHandleAudit ? true : isDisabled ? false : true, message: placeholder, trigger }];
      }
    },
    /**
     * 更新字段
     */
    updateFields(item) {
      console.log('item',item)
      // 字段
      const { curEditFormData, isDisabled, editFormStatus } = this;
      const key = item['fieldName'];
      const value = curEditFormData[key];

      // 赋值(有值才赋值，避免用null 覆盖其他字段，从而造成已填表单字段丢失)
      if (value != undefined && value != null) {
        //  item['initialValue'] = value
        this.$set(item, 'initialValue', value); //$set可以触发更新视图
      }

      // CHECKBOX 类型字段在 表单禁用状态(即明细、审核状态) 下显示 `是` 与 `否`更为直观
      // if (item.type === "CHECKBOX" && editFormStatus === 'readonly') {
      //   const map = { 10041001: '是', 10041002: '否' }
      //   item.type = 'INPUT'
      //   item['initialValue'] = map[Number(item.initialValue)]
      // }
    },
    /**
     * 表单更新，如
     *     1.VIN搜索车辆，带出车辆信息
     *     2.主因配件选择，带出配件信息
     */
    updateForm() {
      this.addFields('update');
    },
    // 基本信息
    createFormList1() {
      const { setStateParam, isReadonly } = this;
      const getFields = () => {
        const arr = [{ type: 'INPUT', label: '质量报告主题', fieldName: 'caseMain', selfCols: 4 }];
        // 只读状态下 才显示报告状态
        isReadonly && arr.unshift({ type: 'SELECT', label: '状态', fieldName: 'reportStatus', itemList: this.createDictList('5003') });
        return arr;
      };
      let fieldList = [
        ...getFields(),
        { type: 'INPUT', label: '质量报告单号', fieldName: 'reportNo', disabled: true, rules: [{ required: false, message: '请输入标题名称', trigger: 'blur' }] },
        { type: 'INPUT', label: '报告人', fieldName: 'reporter', initialValue: '', disabled: true, rules: [{ required: false }] },
        { type: 'INPUT', label: '联系方式', fieldName: 'phone', initialValue: this.userInfo ? this.userInfo.phone : '', disabled: true, rules: [{ required: false }] },
        { type: 'INPUT', label: '报告日期', fieldName: 'applyAt', disabled: true, initialValue: moment().format('YYYY-MM-DD hh:mm:ss'), rules: [{ required: false }] },
        { type: 'INPUT', label: '服务中心代码', fieldName: 'dealerCode', disabled: true, initialValue: '', rules: [{ required: false }] },
        { type: 'INPUT', label: '服务中心名称', fieldName: 'dealerName', disabled: true, initialValue: '', rules: [{ required: false }] },
      ];
      return fieldList;
    },
    //车辆信息
    createFormList2() {
      let fieldList = [
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin',
          readonly: true,
          unitRender: (p) => {
            return (
              <div>
                <multiuse-button icon="el-icon-search" onClick={() => this.$emit('onShow')} />
              </div>
            );
          },
          onInput: (val) => {
            setStateParam('searchVin', val);
          },
        },
        { type: 'INPUT', label: '车系', fieldName: 'seriesName', disabled: true, rules: [{ required: false }] },
        { type: 'INPUT', label: '车型', fieldName: 'modelName', disabled: true, rules: [{ required: false }] },
        { type: 'INPUT', label: '年款', fieldName: 'yearModel', disabled: true, rules: [{ required: false }] },
        { type: 'INPUT', label: '制造基地', fieldName: 'productingArea', disabled: true, rules: [{ required: false }] },
        { type: 'INPUT', label: '车牌', fieldName: 'licensePlate', disabled: true, rules: [{ required: false }] },
        { type: 'SELECT', label: '能源类型', fieldName: 'energyType', disabled: true, rules: [{ required: false }], itemList: this.createDictList('5564') },
        { type: 'SELECT', label: '车辆属性', fieldName: 'vehicleProperties', disabled: true, rules: [{ required: false }], itemList: this.createDictList('2114')},
        { type: 'INPUT', label: '发动机号', fieldName: 'engineCode', disabled: true, rules: [{ required: false }] },
        { type: 'INPUT', label: '变速器号', fieldName: 'gearboxCode', disabled: true, rules: [{ required: false }] },
        { type: 'INPUT', label: '电池编号', fieldName: 'batteryCode', disabled: true, rules: [{ required: false }] },
        { type: 'INPUT', label: '电机号', fieldName: 'motorCode', disabled: true, rules: [{ required: false }] },
        { type: 'INPUT', label: '生产日期', fieldName: 'prodDate', disabled: true, rules: [{ required: false }] },
        { type: 'INPUT', label: '销售日期', fieldName: 'saleDate', disabled: true, rules: [{ required: false }] },
      ];
      return fieldList;
    },
    //进站信息
    createFormList3() {
      let fieldList = [
        { type: 'DATE', label: '进站日期', fieldName: 'stopDate', format: 'yyyy-MM-dd' },
        {
          type: 'INPUT',
          label: '行驶里程',
          fieldName: 'driveMile',
          unitRender: () => {
            return <span>KM</span>;
          },
        },
        { type: 'DATE', label: '故障日期', fieldName: 'faultDate', format: 'yyyy-MM-dd' },
        {
          type: 'INPUT',
          label: '故障里程',
          fieldName: 'faultMile',
          unitRender: () => {
            return <span>KM</span>;
          },
        },
        { type: 'SELECT', label: '故障分类', fieldName: 'faultType', itemList: this.createDictList('5562') },
        { type: 'SELECT', label: '车辆抛锚', fieldName: 'dropAnchor', itemList: this.createDictList('1004') },
        { type: 'SELECT', label: '相同故障再次进店', fieldName: 'faultAgain', itemList: this.createDictList('1004') },
        { type: 'SELECT', label: '车辆加/改装', fieldName: 'refit', itemList: this.createDictList('1004') },
        {
          type: 'INPUT',
          label: '改装说明',
          fieldName: 'refitRemarks',
          selfCols: 4,
          hidden: true
        },
        { type: 'SELECT', label: '可继续行驶', fieldName: 'isDrive', itemList: this.createDictList('1004') },
        { type: 'SELECT', label: '故障可否再现', fieldName: 'faultReappear', itemList: this.createDictList('1004') },
      ];
      return fieldList;
    },
    //故障信息
    createFormList5() {
      let fieldList = [
        {
          type: 'INPUT',
          label: '发动机转速',
          fieldName: 'rotateSpeed',
          unitRender: () => {
            return <span>rpm</span>;
          },
        },
        {
          type: 'INPUT',
          label: '速度',
          fieldName: 'speed',
          unitRender: () => {
            return <span>KM/h</span>;
          },
        },
        {
          type: 'INPUT',
          label: '动力电池电量',
          fieldName: 'batteryCapacity',
          unitRender: () => {
            return <span>%</span>;
          },
        },
        {
          type: 'INPUT',
          label: '外部温度',
          fieldName: 'externalTemperature',
          unitRender: () => {
            return <span>℃</span>;
          },
        },
        {
          type: 'INPUT',
          label: '冷却液温度',
          fieldName: 'coolantTemperature',
          unitRender: () => {
            return <span>℃</span>;
          },
        },
        {
          type: 'INPUT',
          label: '12V蓄电池电压',
          fieldName: 'batteryVoltage',
          unitRender: () => {
            return <span>V</span>;
          },
        },
        {
          type: 'INPUT',
          label: '油箱油量',
          fieldName: 'tank',
          unitRender: () => {
            return <span>%</span>;
          },
        },
        {
          type: 'INPUT',
          label: '运行模式',
          fieldName: 'runningMode',
          readonly: true,
          selfCols: 4        
        },
        {
          type: 'INPUT',
          label: '载荷谱',
          fieldName: 'loadSpectrum',
          readonly: true,
          selfCols: 3,
        },
        {
          type: 'INPUT',
          label: '何时(支持多选)',
          render: p => {
            return (
              <div>
                <el-select v-model={this.whatTime} disabled={true} multiple placeholder=''>
                  {this.whatTimeList.map(item => (
                    <el-option key={item.value} label={item.value} value={item.value} />
                  ))}
                </el-select>
              </div>
            );
          }
        },
        {
          type: 'INPUT',
          label: '气候/环境条件',
          fieldName: 'weather',
          readonly: true,
          selfCols: 3,
        },
      ];
      return fieldList;
    },
    //咨询信息
    createFormList6() {
      let fieldList = [
        { type: 'TEXT_AREA', label: '客户抱怨', fieldName: 'complatnInfo', maxlength: 300, selfCols: 4 },
        { type: 'TEXT_AREA', label: '故障确认', fieldName: 'faultAffirm', maxlength: 300, selfCols: 4 },
        { type: 'TEXT_AREA', label: '诊断描述', fieldName: 'diagnosticDes', maxlength: 300, selfCols: 4 },
        { type: 'TEXT_AREA', label: '诊断结果', fieldName: 'diagnosis', maxlength: 300, selfCols: 4 },
        { type: 'TEXT_AREA', label: '故障原因', fieldName: 'faultReason', maxlength: 300, selfCols: 4 },
      ];
      return fieldList;
    },
    //维修信息
    createFormList7() {
      const { checkBoxOptions } = this;
      let fieldList = [
        {
          type: 'CHECKBOX',
          label: '是否维修',
          fieldName: 'isReproduce',
          options: checkBoxOptions,
          selfCols: 4,
          rules: [{ required: false }],
        },
        { type: 'DATE', label: '修理/检查完成时间', fieldName: 'examineDate', format: 'yyyy-MM-dd', selfCols: 2, hidden: true },
        {
          type: 'INPUT',
          label: '修理/检查完成里程',
          fieldName: 'examineMile',
          selfCols: 2,
          hidden: true,
          unitRender: () => {
            return <span>公里</span>;
          },
        },
        { type: 'TEXT_AREA', label: '故障原因', fieldName: 'faultCause', selfCols: 4, maxlength: 300, hidden: true },
        { type: 'TEXT_AREA', label: '维修作业', fieldName: 'remedialOperation', selfCols: 4, maxlength: 300, hidden: true },
        { type: 'TEXT_AREA', label: '维修结果', fieldName: 'maintenanceResults', selfCols: 4, maxlength: 300, hidden: true },
      ];
      return fieldList;
    },
    //附件信息
    createFormList8() {
      let fieldList = [
        {
          type: 'UPLOAD_FILE',
          label: '上传文件',
          fieldName: 'applyFileList',
          placeholder: '上传文件...',
          selfCols: 4,
          initialValue: [
            // { name:'test img',url:'https://tse1-mm.cn.bing.net/th/id/R-C.c93b0e029400086e56c798e5c0b31fd2?rik=ZdxU0frNSQKAgA&riu=http%3a%2f%2fwww.electrony.net%2fmedia%2f2016%2f01%2fnewbinglogo.png&ehk=GDspp0uaxjf%2faZg8iYGOOTOfrO5gr%2ft%2bFW6X6iMubdE%3d&risl=&pid=ImgRaw&r=0'}
          ],
          upload: {
            actionUrl: `${config.uploadUrl}/api/file/v1/file/upload`,
            limit: 5,
            // tipText: '只能上传pdf格式'
          },
          change: (res) => {
            console.log(1, '文件上传回调', res);
          },
          rules: [{ required: false }],
        },
        { type: 'TEXT_AREA', label: '备注', fieldName: 'remarks', selfCols: 4, maxlength: 300 },
      ];
      return fieldList;
    },
    //审核信息
    createFormList9() {
      let fieldList = [
        { type: 'INPUT', label: '审核人', fieldName: 'checkBy', disabled: true, initialValue: getUser() },
        { type: 'INPUT', label: '审核时间', fieldName: 'checkAt', disabled: true, initialValue: moment().format('YYYY-MM-DD HH:mm:ss'), width: 400 },
        { type: 'INPUT', label: '审核意见', fieldName: 'suggestion', rules: [{ required: false }], selfCols: 4, maxlength: 200 },
      ];
      return fieldList;
    },
    /**
     * 操作历史
     * table表头和数据源
     */
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: false,
          fixed: 'left',
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        {
          title: '单据状态',
          dataIndex: 'operationStatus',
          sorter: false,
        },
        { title: '操作人', dataIndex: 'operator', sorter: false },
        { title: '操作时间', dataIndex: 'operationTime', sorter: false },
        { title: '操作说明', dataIndex: 'instructions', sorter: false },
      ];
    },
    /**
     * DTC信息
     * table表头和数据源
     */
    creatHeader2() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: false,
          fixed: 'left',
          render: (props) => {
            return <span>{props.$index + 1}</span>;
          },
        },
        { title: 'ECU', dataIndex: 'ecu', sorter: false },
        { title: 'DTC', dataIndex: 'dtc', sorter: false },
        { title: 'DTC描述', dataIndex: 'dtcDes', sorter: false },
        {
          title: '故障类型',
          dataIndex: 'dtcFaultType',
          sorter: false,
          dictItems: [
            { text: '偶发', value: '0' },
            { text: '频发', value: '1' },
            { text: '持续', value: '2' }
          ]
        }
      ];
    },
    /**
     * 备件信息
     * table表头和数据源
     */
    creatHeader3() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: false,
          fixed: 'left',
          render: (props) => {
            return <span>{props.row.$index + 1}</span>;
          },
        },
        { title: '备件代码', dataIndex: 'partCode', sorter: false },
        { title: '备件名称', dataIndex: 'partName', sorter: false },
        {
          title: '数量',
          dataIndex: 'partCount',
          sorter: false,
        },
        {
          title: '更换状态',
          dataIndex: 'changeState',
          sorter: false,
          dictItems: [
            { text: '未更换', value: 0 },
            { text: '已更换', value: 1 },
          ],
        },
      ];
    },
    // 关闭弹窗
    closeDialog() {
      this.$emit('close');
    },
    // 显示弹窗
    showDialog(name) {
      // 使用复杂数据类型，不用借助commit 也能实现其子属性的修改
      this.isShowDialog[name] = true;
    },
    /**
     * 修改 store 中的参数 name 为 value
     */
    setStateParam(name, value) {
      const params = { name, value };
      this.SET_STATE_BY_NAME(params);
    },
    /**
     * 审核
     */
    handleAudit(type) {
      const { reportId, reportNo } = this.rowData;
      const formData = this.$refs.formPanel4.SUBMIT_FORM();
      if (formData) {
        if (type === 'TURN' && !formData.suggestion) {
          this.$notify.error({ type: '提示信息', message: '驳回需要填写审核意见！' });
          return;
        }

        const params = {
          reportNo, //"RE202104250001",//质量报告单号
          reportId,
          reviewButton: type, //通过="PASS";驳回="TURN";拒绝="REFUSE"
          ...formData,
        };
        this.$emit('handleAudit', params);
      }
    },
    formChangeHandle2(val) {
      this.saveData = val;
    },
    formChangeHandle(val) {
      this.saveData = val;
    },
    formChangeHandle3(val) {
      this.saveData = val;
    },
    formChangeHandle4(val) {
      this.saveData = val;
    },
    /**
     * 新增反馈 - 保存、上报操作
     */
    async handleSubmit(type) {
      try {
        /**
         * 校验表单
         */
        let submitData = {};
        const result = await this.$refs.formPanel1.getFormData();
        const { editFormStatus } = this;
        const { reportId } = this.rowData;
        if (result) {
          submitData = result;
          /**
           * 表单全部校验通过
           */
          const map = {
            save: '50031004', // 保存操作
            submit: '50031001', // 上报操作
            // 50031001 // 已提报
            // 50031002 // 审核通过
            // 50031003 // 审核驳回
            // 50031004 // 已保存
            // 50031005 // 已作废
          };
          submitData['reportStatus'] = map[type];

          for (let i = 0; i < submitData.applyFileList.length; i++) {
            submitData.applyFileList[i].title = submitData.applyFileList[i].name;
            submitData.applyFileList[i].fileUrl = submitData.applyFileList[i].url;
          }

          let _res;
          if (editFormStatus === 'add') {
            _res = await reqSave({ ...submitData });
          } else {
            submitData['reportId'] = reportId;
            _res = await reqUpadate({ ...submitData });
          }

          const { resultCode, data, errMsg, message } = _res;
          if (resultCode == 200) {
            this.closeDialog();
            this.$emit('refreshTable');
            this.$notify.success({ title: '提示信息', message: message || '保存成功' });
            this.closeDialog();
          } else {
            this.$notify.error({ title: '提示信息', message: errMsg || message || '操作失败!' });
          }
        }
      } catch (err) {
        /**
         * 任意一个表单未校验通过
         */
        console.warn('表单校验未通过', err);
      }
    },
    /**
     * 获取字典数据
     */
    getDictListByCode(code) {
      code = String(code); // 统一转字符串类型比对
      let dict = this.createDictList(code);
      if (process.env.NODE_ENV === 'development') {
        /**
         * 处于开发环境 且 字典数据长度不大于0时
         * 使用本地 mock 字典数据
         */
        dict = dict.length > 0 ? dict : this.mockDictList(code);
      }
      return dict;
    },
    /**
     * mock 字典数据
     * @return {Array}
     *  [
          {
            text:'升档',
            value: 55721001
          },{
            text:'降档',
            value: 55721002
          },
          ...
        ]
     */
    mockDictList(code) {
      code = String(code); // 统一转字符串类型比对
      const { mockCreateDict } = this;
      let dict = [];
      let dictMap = {
        // 驾驶工况
        5572: mockCreateDict(['升档', '降档', '车辆启动', '车辆起步', '过弯或转弯', '刹车制动', '爬坡', '其他', '全部'], code),
        // 环境工况
        5573: mockCreateDict(['多尘', '严寒', '大雨', '高海拔', '高温', '潮湿', '低温', '正常温度', '其他', '全部'], code),
        // 发生频率
        5574: mockCreateDict(['经常', '很少', '每天几次', '每周几次', '每月几次', '每年几次'], code),
        // 当前车辆状况
        5575: mockCreateDict(['待修复', '验证效果中', '已修复'], code),
        // 旧件实物
        5576: mockCreateDict(['已提前返回', '在服务商现场', '按正常途径返回'], code),
        // 故障模式
        5577: mockCreateDict(
          [
            '换挡困难/乱档',
            '间隙不当',
            '车辆无法形式(动力电池)',
            'SOC充不满(动力电池)',
            '无法充电(动力电池)',
            '07报警(动力电池)',
            '车辆续航里程短(动力电池)',
            '03报警(动力电池)',
            '减速器异响',
            '脱离原位(发生错位/位置偏移)',
            '一长二短',
            '一长三短',
            '一长四短',
            '一长五短',
            '一长六短',
            '开焊/脱掉',
            '接缝调整不当',
            '齿轮损坏、磨损',
            '脱档',
          ],
          code
        ),
        default: [],
      };
      code && (dict = dictMap[code] || dictMap['default']);
      return dict;
    },
    /**
     * 创建字典
     * @return {Object}
     *  {
          text:'升档',
          value: 55721001
        }
     */
    mockCreateDict(textArr, code) {
      code = Number(code);
      const dict = textArr.map((text, i) => {
        return {
          text,
          value: Number(`${code}100${i + 1}`),
        };
      });
      return dict;
    },
  },
};
</script>

<style lang="less" scoped>
.body {
  padding-bottom: 60px;
}
.footer {
  position: fixed;
  right: 24px;
  bottom: 16px;
  width: 94%;
  .box {
    display: flex;
    justify-content: center;
  }
}
// 减少 输入框右padding
::v-deep .el-input--suffix .el-input__inner {
  padding-right: 16px;
}
// 下拉框 右侧padding 保持不变
::v-deep .el-select .el-input__inner {
  padding-right: 32px;
}
// 归零 输入框末尾插入ICON 情况下的右padding
// ::v-deep .el-input-group--append .el-input__inner, .el-input-group__prepend{
//   padding-right:0px;
// }
.null-box {
  display: flex;
  height: 500px;
  justify-content: center;
  align-items: center;
}
</style>
